import re
import os

macro_def_pattern = re.compile(r'#define\s+(\w+)\s+(0x[0-9A-Fa-f]{8})')
magic_number_pattern = re.compile(r'(0x[0-9A-Fa-f]{8})', re.IGNORECASE)

magic_number_dict = {}

def get_magic_number_summary():
    return {"已优化的魔数个数": len(magic_number_dict)}

def extract_magic_number_def(c_project_path):
    for root, dirs, files in os.walk(c_project_path):
        for file in files:
            if file.endswith(('.c', '.h')):
                with open(os.path.join(root, file), 'r') as f:
                    for line in f:
                        macro_match = macro_def_pattern.match(line)
                        if macro_match:
                            
                            macro_name = macro_match.group(1)
                            magic_number_dict[macro_name] = macro_match.group(2)

def manage_magic_number(content):
    matched_magic_number_key_list = []
    for macro_name, magic_number in magic_number_dict.items():
        #magic_number_match = magic_number_pattern.fullmatch(magic_number)
        #if magic_number_match:
        #    content = content.replace(magic_number, macro_name)
        #    matched_magic_number_key_list.append(macro_name)

        magic_number_match = content.find(str(magic_number).lower()) != -1
        if magic_number_match:
            content = content.replace(str(magic_number).lower(), macro_name)
            matched_magic_number_key_list.append(macro_name)

        magic_number_match = content.find(str(magic_number).upper().replace('X', 'x')) != -1
        if magic_number_match:
            content = content.replace(str(magic_number).upper().replace('X', 'x'), macro_name)
            matched_magic_number_key_list.append(macro_name)
        # 在.rs文件头部加上宏的定义
    if len(matched_magic_number_key_list) != 0:
        new_content = """macro_rules! magic_number {
    ($name:ident, $value:expr) => {
        const $name: u32 = $value;
    };
}
""" + '\n'.join([f'magic_number!({macro_name}, {magic_number});' for macro_name, magic_number in magic_number_dict.items() if macro_name in matched_magic_number_key_list])  + '\n'+ content
    else:
        new_content = content
    return new_content
